package com.dzl.moive.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzl.moive.pojo.WelfareMovieCinema;
import com.dzl.moive.pojo.WelfareMovieCity;
import com.dzl.moive.pojo.WelfareMovieInfo;
import com.dzl.moive.pojo.WelfareMovieOrder;
import com.dzl.moive.pojo.dto.WelfareMovieOrderSaveDto;
import com.dzl.moive.pojo.vo.WelfareMovieOpiDetailVo;
import com.dzl.moive.pojo.vo.WelfareMovieTicketVo;
import com.dzl.util.DateUtil;
import com.dzl.util.EmptyUtils;
import com.dzl.util.HttpUtil;
import com.dzl.util.RedisUtil;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;

/**
 * @Description:嘟嘟电影api接口相关公用方法处理
 * @author liuguanjun
 * @time:2021年10月21日 11:53:00
 */
public class MovieUtils {

    /**
     * 请求嘟嘟电影接口提交数据
     * @param method 接口名称
     * @param dicArg 接口所需参数
     * @author liuguanjun
     * @date 2021.10.21 11:53
     */
    public static String postData(String method, Map dicArg) {
        dicArg.put("timestamp", DateUtil.getNow());
        dicArg.put("appkey", MovieConstant.COMMON_PARAM.appkey);
        dicArg.put("v", MovieConstant.COMMON_PARAM.v);
        dicArg.put("method", method);
        //sign签名
        String sSignPara = getSignPara(dicArg);
        String sSign = doMD5(sSignPara+MovieConstant.COMMON_PARAM.privatekey,null);
        dicArg.put("sign", sSign);
        return HttpUtil.sendPost(MovieConstant.HOST_URL,dicArg,"utf-8");
    }


    protected  static String getSignPara(Map dicArg) {
        StringBuilder prestr = new StringBuilder();
        Iterator<Map.Entry<String, Object>> iterator = dicArg.entrySet().iterator();
        List<String> paramKeyList = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            String key=entry.getKey();
            if ( key == "sign" ||  key== "privatekey")
                continue;
            paramKeyList.add(entry.getKey());
        }
        Collections.sort(paramKeyList);
        for (String str:paramKeyList) {
            prestr.append(str +"="+ dicArg.get(str)+"&");
        }
        return prestr.substring(0,prestr.length()-1);
    }

    /**
     * 数组
     * */
    private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };


    /**
     * 字符串重写
     * @param b
     * @return
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    /**
     * byteToHesString
     * */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * MD5加密
     * @param origin
     * @param charsetname
     * @return
     */
    public static String doMD5(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
            resultString = null;
        }
        return resultString;
    }

    //获取购票城市列表
    public static List<WelfareMovieCity> getMovieCityList(){
        String sMethod = MovieConstant.API_URL.GET_CITY_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieCityList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("cityList");
            List<WelfareMovieCity> list = JSONObject.parseArray(jsonArray.toJSONString(),WelfareMovieCity.class);
            return list;
        }
        return null;
    }

    //获取购票城市区县列表
    public static List<WelfareMovieCity> getMovieCountyList(String citycode){
        String sMethod = MovieConstant.API_URL.GET_COUNTY_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("citycode",citycode);
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieCountyList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("countyList");
            List<WelfareMovieCity> list = JSONObject.parseArray(jsonArray.toJSONString(),WelfareMovieCity.class);
            return list;
        }
        return null;
    }

    //获取购票城市热映电影列表
    public static List<WelfareMovieInfo> getMovieHotList(String citycode){
        Object object = RedisUtil.get("movieHotList");
        if(EmptyUtils.isNotEmpty(object)){
            List<WelfareMovieInfo> list = (List<WelfareMovieInfo>) object;
            return list;
        }
        String sMethod = MovieConstant.API_URL.GET_MOVIE_HOT_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("citycode",citycode);
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieHotList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("movieList");
            if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
                List<WelfareMovieInfo> list = JSONObject.parseArray(jsonArray.toJSONString(),WelfareMovieInfo.class);
                RedisUtil.set("movieHotList", list,60*60*1);//缓存1小时
                return list;
            }
        }
        return null;
    }

    //获取即将上映电影列表
    public static List<WelfareMovieInfo> getMovieFutureList(String citycode){
        Object object = RedisUtil.get("movieFutureList");
        if(EmptyUtils.isNotEmpty(object)){
            List<WelfareMovieInfo> list = (List<WelfareMovieInfo>) object;
            return list;
        }
        String sMethod = MovieConstant.API_URL.GET_MOVIE_FUTURE_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("citycode",citycode);
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieFutureList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("movieList");
            if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
                List<WelfareMovieInfo> list = JSONObject.parseArray(jsonArray.toJSONString(),WelfareMovieInfo.class);
                RedisUtil.set("movieFutureList", list,60*60*6);//缓存6小时
                return list;
            }
        }
        return null;
    }

    //影片详细信息
    public static WelfareMovieInfo getMovieDetail(Integer movieid,String citycode){
        String sMethod = MovieConstant.API_URL.GET_MOVIE_DETAIL;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("movieid",movieid+"");
        if(EmptyUtils.isNotEmpty(citycode)){
            dicArg.put("citycode",citycode);
        }
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieDetail================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONObject jsonObject1 =  dataJsonObject.getJSONObject("movie");
            if(EmptyUtils.isNotEmpty(jsonObject1)){
                WelfareMovieInfo welfareMovieInfo = JSONObject.parseObject(jsonObject1.toJSONString(),WelfareMovieInfo.class);
                return welfareMovieInfo;
            }
        }
        return null;
    }

    //获取电影影院列表
    public static List<WelfareMovieCinema> getMovieCinemaList(String citycode, Integer pageNo, Integer pageSize){
        String sMethod = MovieConstant.API_URL.GET_CINEMA_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("citycode",citycode);
        dicArg.put("page_no",pageNo+"");
        dicArg.put("per",pageSize+"");
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieCinemaList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("cinemaList");
            if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
                List<WelfareMovieCinema> list = JSONObject.parseArray(jsonArray.toJSONString(),WelfareMovieCinema.class);
                return list;
            }
        }
        return null;
    }

    //影片开放购票的影院
    public static String getMoviePlayCinemaList(Integer movieid,String citycode,String playdate){
        String sMethod = MovieConstant.API_URL.GET_MOVIE_PLAY_CINEMA_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("movieid",movieid+"");
        dicArg.put("citycode",citycode);
        if(EmptyUtils.isNotEmpty(playdate)){
            dicArg.put("playdate",playdate);
        }
        String result = postData(sMethod, dicArg);
        System.out.println("getMoviePlayCinemaList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            String cinemaids =  dataJsonObject.getString("cinemaids");
            return cinemaids;
        }
        return null;
    }

    //影院详细信息
    public static WelfareMovieCinema getCinemaDetail(Integer cinemaid){
        String sMethod = MovieConstant.API_URL.GET_CINEMA_DETAIL;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("cinemaid",cinemaid+"");
        String result = postData(sMethod, dicArg);
        System.out.println("getCinemaDetail================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONObject jsonObject1 =  dataJsonObject.getJSONObject("cinema");
            if(EmptyUtils.isNotEmpty(jsonObject1)){
                WelfareMovieCinema welfareMovieCinema = JSONObject.parseObject(jsonObject1.toJSONString(),WelfareMovieCinema.class);
                return welfareMovieCinema;
            }
        }
        return null;
    }

    //影院排片列表
    public static List<WelfareMovieOpiDetailVo> getMovieOpiList(Integer cinemaid){
        String sMethod = MovieConstant.API_URL.GET_OPI_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("cinemaid",cinemaid+"");
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieOpiList================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray =  dataJsonObject.getJSONArray("opilist");
            if(EmptyUtils.isNotEmpty(jsonArray) && jsonArray.size()>0){
                List<WelfareMovieOpiDetailVo> list = JSONObject.parseArray(jsonArray.toJSONString(), WelfareMovieOpiDetailVo.class);
                return list;
            }
        }
        return null;
    }


    //排片详情
    public static WelfareMovieOpiDetailVo getOpiDetail(String opiid){
        String sMethod = MovieConstant.API_URL.GET_OPI_DETAIL;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("opiid",opiid);
        String result = postData(sMethod, dicArg);
        System.out.println("getOpiDetail================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            if(EmptyUtils.isNotEmpty(data)){
                JSONObject dataJsonObject = JSONObject.parseObject(data);
                JSONObject jsonObject1 =  dataJsonObject.getJSONObject("opi");
                if(jsonObject1!=null){
                    WelfareMovieOpiDetailVo welfareMovieCinemaOpiVo = JSONObject.parseObject(jsonObject1.toJSONString(), WelfareMovieOpiDetailVo.class);
                    return welfareMovieCinemaOpiVo;
                }
            }
        }
        return null;
    }

    //排片详情
    public static WelfareMovieTicketVo getOpiSeat(String opiid){
        String sMethod = MovieConstant.API_URL.GET_OPI_SEAT;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("opiid",opiid);
        String result = postData(sMethod, dicArg);
        System.out.println("getOpiSeat================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            if(EmptyUtils.isNotEmpty(data)){
                JSONObject dataJsonObject = JSONObject.parseObject(data);
                if(dataJsonObject!=null){
                    //JSONObject jsonObject1 =  dataJsonObject.getJSONObject("opi");
                    //System.out.println(jsonObject1.getString("tip_message"));
                    //JSONArray jsonArray =  dataJsonObject.getJSONArray("seatList");
                    WelfareMovieTicketVo welfareMovieOpiSeatVo = JSONObject.parseObject(dataJsonObject.toJSONString(), WelfareMovieTicketVo.class);
                    return welfareMovieOpiSeatVo;
                }
            }
        }
        return null;
    }

    //生成订单
    public static String createMovieOrder(WelfareMovieOrderSaveDto welfareOrderSaveDto){
        String sMethod = MovieConstant.API_URL.ORDER_CREATE;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("opiid",welfareOrderSaveDto.getOpiid());
        dicArg.put("seatids",welfareOrderSaveDto.getSeatids());
        dicArg.put("seatnames",welfareOrderSaveDto.getSeatnames());
        dicArg.put("mobile",welfareOrderSaveDto.getMobile());
        if(EmptyUtils.isNotEmpty(welfareOrderSaveDto.getTotalSettleAmount())){
            dicArg.put("totalSettleAmount",welfareOrderSaveDto.getTotalSettleAmount().toString());
        }
        String result = postData(sMethod, dicArg);
        System.out.println("createMovieOrder================>"+result);
        return result;
        /*JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            return   dataJsonObject.getString("tradeno");
        }else{
            String data =  jsonObject.getString("error");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            return "fail:code="+dataJsonObject.getString("code")+",desp="+dataJsonObject.getString("desp");
        }*/
    }

    //取消订单
    public static String cancelMovieOrder(String tradeno){
        String sMethod = MovieConstant.API_URL.ORDER_CANCEL;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("tradeno",tradeno);
        String result = postData(sMethod, dicArg);
        System.out.println("cancelMovieOrder================>"+result);
        return result;
        /*JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getBoolean("success");*/
    }

    //获取用户有效期内未支付的订单
    public static String getUnpaidMovieOrder(String mobile){
        String sMethod = MovieConstant.API_URL.GET_UNPAID_ORDER_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("mobile",mobile);
        String result = postData(sMethod, dicArg);
        System.out.println("getUnpaidMovieOrder================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            if(EmptyUtils.isNotEmpty(dataJsonObject)){
                return   dataJsonObject.getString("tradeno");
            }
        }
        return null;
    }

    //获取电影票订单详情
    public static WelfareMovieOrder getMovieOrderDetail(String tradeno){
        String sMethod = MovieConstant.API_URL.GET_ORDER_DETAIL_TICKETCODE_JSON;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("tradeno",tradeno);
        String result = postData(sMethod, dicArg);
        System.out.println("getMovieOrderDetail================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getBoolean("success")){
            String data =  jsonObject.getString("data");
            JSONObject dataJsonObject = JSONObject.parseObject(data);
            JSONObject jsonObject1 =  dataJsonObject.getJSONObject("order");
            if(EmptyUtils.isNotEmpty(jsonObject1)){
                WelfareMovieOrder welfareMovieOrder = JSONObject.parseObject(jsonObject1.toJSONString(),WelfareMovieOrder.class);
                JSONArray jsonArray=(JSONArray) jsonObject1.get("ticketcodeList");
                if(EmptyUtils.isNotEmpty(jsonArray)){
                    //List<WelfareMovieOrderTicketcodeList> welfareMovieOrderTicketcodeLists = JSONObject.parseArray(jsonArray.toJSONString(), WelfareMovieOrderTicketcodeList.class);
                    welfareMovieOrder.setTicketcode(jsonArray.toJSONString());
                }
                return welfareMovieOrder;
            }
        }
        return null;
    }

    //订单支付通知:合作方订单付款后，通知给嘟电影，嘟电影处理后续的出票逻辑，未付款订单不允许通知给嘟电影，如果因为网络原因没有通知成功，合作方方需要有重复通知机制
    public static Boolean updateMovieOrderPayNotify(String tradeno,String partnerTradeno){
        String sMethod = MovieConstant.API_URL.ORDER_PAY_NOTIFY;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("tradeno",tradeno);
        dicArg.put("partner_tradeno",partnerTradeno);
        String result = postData(sMethod, dicArg);
        System.out.println("updateMovieOrderPayNotify================>"+result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getBoolean("success");
    }

    public static void main(String[] args) throws IOException {
        //影片开放购票的影院
        /*String sMethod = MovieConstant.API_URL.GET_MOVIE_PLAY_CINEMA_LIST;
        HashMap<String,Object> dicArg = new HashMap<>();
        dicArg.put("movieid", "4302");
        dicArg.put("citycode", "310100");
        dicArg.put("playdate", "2021-11-25");
        String result = postData(sMethod, dicArg);
        System.out.println(result);*/

        getMovieOrderDetail("12111301802480769");
        //getMovieCityList();
       // getMovieCountyList("420100");
        //getMovieHotList("420100");
        //getMovieFutureList("420100");
       // getMovieDetail(542326,"420100");
       // getMovieCinemaList("440300",13,20);
       // getMoviePlayCinemaList(542326,"420100","2021-10-28");
        //getCinemaDetail(30949);
       // getMovieOpiList(30949);
       // getOpiDetail("a_45d75d98e8ddff9026ea2e27bb47a367");
        //getOpiSeat("a_45d75d98e8ddff9026ea2e27bb47a367");

       // String s = "0|1|0";
        //s.split("\\|");
        //System.out.println(s.split("\\|")[1]);
        /*String ticketcode = "您已定11月11日10:00烽禾影城（泛悦奥特莱斯店全VIP真皮沙发）影票2张，凭T序列号808818,T验证码980623至影院取票机或柜台取票。客服电话";
        ticketcode = ticketcode.split("序列号")[1];
        if(EmptyUtils.isNotEmpty(ticketcode)){
            ticketcode = ticketcode.split("至影院")[0];
            ticketcode = ticketcode.replaceAll(",","");
            ticketcode = ticketcode.replaceAll("T","");
            ticketcode = ticketcode.replaceAll("验证码","|");
        }*/
        //String str = getUnpaidMovieOrder("13871264775");
        /*String str = cancelMovieOrder("12111301552099988");
        System.out.println(str);*/

    }






}
